package com.xyht.sca_s.student_manage_system.modules.card.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ExceptionCast;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.CacheUtil;
import com.xyht.sca_s.student_manage_system.modules.card.entity.SmsCard;
import com.xyht.sca_s.student_manage_system.modules.card.entity.SmsCardDetail;
import com.xyht.sca_s.student_manage_system.modules.card.entity.SmsCardProcess;
import com.xyht.sca_s.student_manage_system.modules.card.entity.SmsCardProcessLevel;
import com.xyht.sca_s.student_manage_system.modules.card.entity.req.SmsCardAddReq;
import com.xyht.sca_s.student_manage_system.modules.card.mapper.SmsCardDetailMapper;
import com.xyht.sca_s.student_manage_system.modules.card.mapper.SmsCardMapper;
import com.xyht.sca_s.student_manage_system.modules.card.mapper.SmsCardProcessLevelMapper;
import com.xyht.sca_s.student_manage_system.modules.card.mapper.SmsCardProcessMapper;
import com.xyht.sca_s.student_manage_system.modules.card.service.SmsCardService;
import com.xyht.sca_s.student_manage_system.modules.org.entity.SmsOrgStructure;
import com.xyht.sca_s.student_manage_system.modules.org.entity.SmsOrgUserRelation;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgStructureMapper;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgUserRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.student.entity.SmsStudentInfo;
import com.xyht.sca_s.student_manage_system.modules.student.entity.SmsUserStudentRelation;
import com.xyht.sca_s.student_manage_system.modules.student.mapper.SmsStudentInfoMapper;
import com.xyht.sca_s.student_manage_system.modules.student.mapper.SmsUserStudentRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.teacher.mapper.SmsTeacherInfoMapper;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUserRoleRelation;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsRoleMapper;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserRoleRelationMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.leave.constant.LeaveAllowFlag.ALLOW_FLAG_WAIT;
import static com.xyht.sca_s.student_manage_system.modules.org.constants.OrgTypeConstant.ORG_TYPE_CLASS;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.RoleIDConstant.ROLE_STUDENT_ID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2023-01-20
 */
@Service
public class SmsCardServiceImpl extends ServiceImpl<SmsCardMapper, SmsCard> implements SmsCardService {
    @Autowired
    private SmsUserRoleRelationMapper smsUserRoleRelationMapper;
    @Autowired
    private SmsUserStudentRelationMapper smsUserStudentRelationMapper;
    @Autowired
    private SmsStudentInfoMapper smsStudentInfoMapper;
    @Autowired
    private SmsOrgUserRelationMapper smsOrgUserRelationMapper;
    @Autowired
    private SmsOrgStructureMapper smsOrgStructureMapper;
    @Autowired
    private SmsCardMapper smsCardMapper;
    @Autowired
    private SmsCardProcessMapper smsCardProcessMapper;
    @Autowired
    private SmsCardProcessLevelMapper smsCardProcessLevelMapper;
    @Autowired
    private SmsTeacherInfoMapper smsTeacherInfoMapper;
    @Autowired
    private SmsUserMapper smsUserMapper;
    @Autowired
    private SmsRoleMapper smsRoleMapper;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private SmsCardDetailMapper smsCardDetailMapper;

    @Override
    public ResponseResult addCard(SmsCardAddReq smsCardAddReq, String user_id) {
        if (isNullOrEmpty(smsCardAddReq.getProcessId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsCard smsCard;

        //用户角色校验
        QueryWrapper<SmsUserRoleRelation> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(SmsUserRoleRelation::getUserId, user_id)
                .eq(SmsUserRoleRelation::getRoleId, ROLE_STUDENT_ID);
        SmsUserRoleRelation adminRole = smsUserRoleRelationMapper.selectOne(queryWrapper);
        if (adminRole == null) {
            return CommonResult.failed(CommonCodeEnum.APPLY_ROLE_NOT_EXIST);
        }

        //用户信息校验
        QueryWrapper<SmsUserStudentRelation> userStudentRelationQueryWrapper = new QueryWrapper<>();
        userStudentRelationQueryWrapper.lambda().eq(SmsUserStudentRelation::getUserId, user_id);
        SmsUserStudentRelation userStudentRelation = smsUserStudentRelationMapper.selectOne(userStudentRelationQueryWrapper);
        if (userStudentRelation == null) {
            return CommonResult.failed(CommonCodeEnum.USER_NOT_STUDENT_INFO);
        }
        SmsStudentInfo smsStudentInfo = smsStudentInfoMapper.selectById(userStudentRelation.getStuId());
        if (smsStudentInfo == null) {
            return CommonResult.failed(CommonCodeEnum.USER_NOT_STUDENT_INFO);
        }

        //用户组织班级校验
        QueryWrapper<SmsOrgUserRelation> orgUserRelationQueryWrapper = new QueryWrapper<>();
        orgUserRelationQueryWrapper.lambda().eq(SmsOrgUserRelation::getUserId, user_id);
        List<SmsOrgUserRelation> orgUserRelationList = smsOrgUserRelationMapper.selectList(orgUserRelationQueryWrapper);
        if (orgUserRelationList == null || orgUserRelationList.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.USER_NOT_ORG_INFO);
        }
        List<String> orgIDList = orgUserRelationList.stream().map(SmsOrgUserRelation::getOrgId).collect(Collectors.toList());
        QueryWrapper<SmsOrgStructure> orgStructureQueryWrapper = new QueryWrapper<>();
        orgStructureQueryWrapper.lambda().in(SmsOrgStructure::getId, orgIDList).eq(SmsOrgStructure::getLevel, ORG_TYPE_CLASS);
        List<SmsOrgStructure> orgStructureList = smsOrgStructureMapper.selectList(orgStructureQueryWrapper);
        if (orgStructureList == null || orgStructureList.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.USER_NOT_CLASS_INFO);
        }
        Integer stuClassOrgId = orgStructureList.get(0).getId();

        //用户是否有在申请中
        QueryWrapper<SmsCard> leaveQueryWrapper = new QueryWrapper<>();
        leaveQueryWrapper.lambda().eq(SmsCard::getUserId, user_id)
                .eq(SmsCard::getIsAllow, ALLOW_FLAG_WAIT);
        List<SmsCard> smsCardList = smsCardMapper.selectList(leaveQueryWrapper);
        if (smsCardList != null && smsCardList.size() > 0) {
            return CommonResult.failed(CommonCodeEnum.CARD_APPLY_EXIST);
        }


        smsCard = new SmsCard();
        BeanUtils.copyProperties(smsCardAddReq, smsCard);
        //获取相应证件补办流程
        QueryWrapper<SmsCardProcess> cardProcessQueryWrapper = new QueryWrapper<>();
        cardProcessQueryWrapper.lambda().eq(SmsCardProcess::getId, smsCardAddReq.getProcessId());
        List<SmsCardProcess> cardProcessList = smsCardProcessMapper.selectList(cardProcessQueryWrapper);
        if (cardProcessList != null && cardProcessList.size() == 1) {
            smsCard.setProcessId(cardProcessList.get(0).getId());
        } else {
            return CommonResult.failed(CommonCodeEnum.PROCESS_ERR);
        }

        //保存
        smsCard.setStuName(smsStudentInfo.getStuName());
        smsCard.setStuNo(smsStudentInfo.getStuNo());
        smsCard.setUserId(user_id);
        smsCard.setStuId(userStudentRelation.getStuId());
        smsCard.setStuClass(stuClassOrgId.toString());
        smsCardMapper.insert(smsCard);
        if (isNullOrEmpty(smsCard.getId())) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
        }

        //保存审批流程
        QueryWrapper<SmsCardProcessLevel> cardProcessLevelQueryWrapper = new QueryWrapper<>();
        cardProcessLevelQueryWrapper.lambda().eq(SmsCardProcessLevel::getProcessId, smsCard.getProcessId())
                .orderByAsc(SmsCardProcessLevel::getSort);
        List<SmsCardProcessLevel> cardProcessLevelList = smsCardProcessLevelMapper.selectList(cardProcessLevelQueryWrapper);
        if (cardProcessLevelList != null && cardProcessLevelList.size() > 0) {
            for (SmsCardProcessLevel processLevel : cardProcessLevelList) {
                //获取角色名
                String roleName = smsRoleMapper.selectById(processLevel.getRoleId()).getRoleName();

                SmsCardDetail smsCardDetail = new SmsCardDetail();
                smsCardDetail.setAllowSort(processLevel.getSort());
                smsCardDetail.setCardId(smsCard.getId());
                smsCardDetail.setRoleId(processLevel.getRoleId());
                smsCardDetail.setRoleName(roleName);
                smsCardDetailMapper.insert(smsCardDetail);
            }
        }
        return CommonResult.success();
    }
}
